package com.ddd.mill.domain.aggregate.product;

import com.ddd.mill.api.product.dto.request.SaveProductByAdminDto;
import com.ddd.mill.api.product.dto.response.UpdateStatusDto;

import com.ddd.mill.domain.aggregate.constant.product.constant.ProductNoConstant;
import com.ddd.mill.domain.aggregate.constant.product.constant.ProductStatusEnum;
import com.ddd.mill.domain.aggregate.product.entity.Product;
import com.ddd.mill.domain.aggregate.product.entity.ProductDetail;
import com.ddd.mill.domain.aggregate.product.entity.ProductImg;
import com.ddd.mill.domain.aggregate.product.repository.ProductDetailRepository;
import com.ddd.mill.domain.aggregate.product.repository.ProductImgRepository;
import com.ddd.mill.domain.aggregate.product.repository.ProductRepository;
import com.ddd.mill.infrastructure.exception.BizException;
import com.ddd.mill.infrastructure.persistent.domain.BaseAggregate;
import com.ddd.mill.infrastructure.utils.OrderNoGenerator;
import com.ddd.mill.infrastructure.utils.TypeConvertUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author liu
 * @title: ProductAggregate
 * @projectName trading-center
 * @date 2020/11/3011:00
 */
@Slf4j
@Service
public class ProductAggregate extends BaseAggregate {
    @Resource
    private OrderNoGenerator orderNoGenerator;
    @Resource
    private ProductRepository productRepository;
    @Resource
    private ProductDetailRepository productDetailRepository;
    @Resource
    private ProductImgRepository productImgRepository;

    @Transactional(rollbackFor = Exception.class)
    public Long saveProduct(SaveProductByAdminDto dto,Long adminId){
        //保存基本信息
        Product product = TypeConvertUtils.convert(dto, Product.class);
        product.setProductNo(orderNoGenerator.nextNo("QNran{6}", ProductNoConstant.orderNoGenerator));
        if (null==productRepository.save(product)){
            log.error("产品详情保存失败，id={}", product.getId());
            throw new BizException("保存失败");
        }
        //保存详细信息
        ProductDetail productDetail = new ProductDetail();
        productDetail.setCreatorId(adminId);
        productDetail.setProductId(product.getId());
        productDetail.setDetail(dto.getDetail());
        productDetail.setDeliverTips(dto.getDeliverTips());
        productDetail.setEditorId(adminId);
        if(null==productDetailRepository.save(productDetail)){
            log.error("产品详情保存失败，id={}", product.getId());
            throw new BizException("保存失败");
        }
        //保存图片和视频
        List<ProductImg> productImgList = new ArrayList<>();
        for (String s : dto.getImageUrls()){
            ProductImg productImg = new ProductImg();
            productImg.setProductId(product.getId());
            productImg.setImgUrl(s);
            productImg.setCreatorId(adminId);
            productImg.setEditorId(adminId);
            productImgList.add(productImg);
        }
        for (String s : dto.getVideoUrls()){
            ProductImg productImg = new ProductImg();
            productImg.setProductId(product.getId());
            productImg.setImgUrl(s);
            productImg.setCreatorId(adminId);
            productImg.setEditorId(adminId);
            productImgList.add(productImg);
        }
        productImgRepository.saveBatch(productImgList);
        return product.getId();
    }

    public void updateStatus(Long id, UpdateStatusDto request, Long adminId){
        if (null==productRepository.load(id)){
            throw new BizException("产品不存在");
        }
        Product product = new Product();
        product.setId(id);
        product.setStatus(request.getStatus());
        product.setEditorId(adminId);
        productRepository.save(product);
    }

    @Transactional(rollbackFor = Exception.class)
    public void deleteProduct(String[] idList, Long adminId){
        for (String idStr : idList) {
            try {
                Long id = Long.parseLong(idStr);
                Product product = productRepository.load(id);
                if (product == null) {
                    throw new BizException("id为" + id + "的产品不存在");
                }
                if (product.getStatus().equals(ProductStatusEnum.PUT_ON_SALE)) {
                    throw new BizException("产品：" + product.getName() + "上架中，不能删除");
                }
                //todo 查询有无该商品的订单
//            QueryWrapper queryWrapper = new QueryWrapper();
//            queryWrapper.eq("product_id", id);
//            int count = orderBaseService.count(queryWrapper);
//            if (count > 0) {
//                throw new BizException("产品：" + product.getName() + "已产生订单，不能删除");
//            }
                productRepository.removeById(id);
            }catch (Exception e){
                throw new BizException("删除失败");
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void copyProduct( Long adminId, Product product) throws Exception {
        Long productId=product.getId();
        // 复制基本信息
        productRepository.mustBeExisted(productId);
        product.setId(null);
        product.setProductNo(orderNoGenerator.nextNo("QNran{6}", "bxeProduct"));
        product.setViewNum(0);
        product.setSoldNum(0);
        product.setCreatorId(adminId);
        product.setEditorId(adminId);
        if (null==productRepository.save(product)){
            throw new BizException(product.getName()+"产品复制失败");
        }
        // 详情
        ProductDetail productDetail = productDetailRepository.getByProductId(productId);
        productDetail.setId(null);
        productDetail.setProductId(product.getId());
        productDetail.setCreatorId(adminId);
        productDetail.setEditorId(adminId);
        if (null==productDetailRepository.save(productDetail)){
            throw new BizException(product.getName()+"产品复制失败");
        }
        // 轮播图
        List<ProductImg> productImgList = productImgRepository.getListByProductId(productId);
        for (ProductImg p : productImgList){
            p.setId(null);
            p.setProductId(product.getId());
            p.setCreatorId(adminId);
            p.setEditorId(adminId);
        }
        productImgRepository.saveBatch(productImgList);

    }

}
